package com.laikan.reader.bookstore.activity;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Handler;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.WindowManager;
import android.view.inputmethod.EditorInfo;
import android.view.inputmethod.InputMethodManager;
import android.widget.*;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.TextView.OnEditorActionListener;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import com.google.gson.reflect.TypeToken;
import com.laikan.library.components.activitys.BasicActivity;
import com.laikan.library.httpvolley.engine.HttpApiRequestEngine;
import com.laikan.library.httpvolley.engine.Requester;
import com.laikan.library.httpvolley.helper.RequestListener;
import com.laikan.library.httpvolley.helper.VolleyErrorHandler;
import com.laikan.library.httpvolley.response.HttpResponse;
import com.laikan.library.managers.ToastMgr;
import com.laikan.library.utils.SPUtil;
import com.laikan.reader.R;
import com.laikan.reader.bookreader.activity.BookDesActivity;
import com.laikan.reader.comment.APIProtocol;
import com.laikan.reader.comment.Constants;
import com.laikan.reader.core.adapter.SearchContentAdapter;
import com.laikan.reader.core.bean.BaseDataBean;
import com.laikan.reader.core.bean.Search;
import com.laikan.reader.core.bean.SearchData;
import com.laikan.reader.core.utils.ActivityUitl;
import com.laikan.reader.core.utils.PublicUtil;
import com.laikan.reader.core.view.CircleProgressBar;
import com.laikan.reader.core.view.MultipleTextView;
import com.laikan.reader.core.view.MultipleTextView.OnMultipleTVItemClickListener;
import com.laikan.reader.core.view.ProgressBar_Modern;
import com.laikan.reader.core.view.SnackBarNotice;
import com.socks.library.KLog;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

public class BookSearchActivity extends BasicActivity implements OnClickListener, TextWatcher {

    private AutoCompleteTextView auto_tv_book_search;

    private List<Search> mBookBeanList;
    private List<String> mRecommendDataList = new ArrayList<>();
    private SearchContentAdapter BookSearchAdapter;
    private String searchContent;
    private boolean mIsBookSearchList = false;
    private long mLoadDelaynternalTime;
    private boolean mIsSearchRequestFinish = true;
    private ScrollView search_scroll;
    private int mCurrentPage = 1;

    private MultipleTextView multiple_tv_recommend, multiple_tv_book_searchrecord;
    private String[] mBookSearchRecord;
    private ImageView iv_back, iv_clear_searchtext, iv_refresh_recommend, iv_clear_book_searchrecord;
    private ListView lv_book_search;
    private ProgressBar_Modern mModernLoadProgressBar;
    private RelativeLayout rl_book_search_btn, back_layout, common_loaddata_notice;
    private TextView tv_recommend_name, common_prompt_content, common_refresh_net;
    private CircleProgressBar circleProgressBar;
    private View search_foot_view;
    Drawable drawable_back_tv;


    public void searchBookData() {
        searchContent = auto_tv_book_search.getText().toString();
        auto_tv_book_search.clearFocus();
        if (TextUtils.isEmpty(searchContent.trim())) {
            ToastMgr.showShortToast(R.string.search_enter_empty);
            mIsSearchRequestFinish = true;
        }else {
            resetData();
            hideSoftkeyBoard(auto_tv_book_search);
            saveHistory(auto_tv_book_search);
            requestSearchData();
        }
        refreshSearchRecord();
    }

    @Override
    protected void onPause() {
        super.onPause();
        auto_tv_book_search.clearFocus();
    }

    @Override
    protected void onResume() {
        super.onResume();
    }

    @Override
    protected void assignViews() {
        search_foot_view = View.inflate(mContext, R.layout.search_new_foot_view, null);
        setContentView(R.layout.lk_search_new);
        search_scroll = (ScrollView)findViewById(R.id.search_scroll);
        iv_back = (ImageView)findViewById(R.id.iv_back);
        back_layout = (RelativeLayout)findViewById(R.id.back_layout);
        iv_clear_searchtext = (ImageView)findViewById(R.id.iv_clear_searchtext);
        iv_clear_book_searchrecord = (ImageView)findViewById(R.id.iv_clear_book_searchrecord);
        auto_tv_book_search = (AutoCompleteTextView)findViewById(R.id.auto_tv_book_search);
        auto_tv_book_search.setCursorVisible(false);
        multiple_tv_recommend = (MultipleTextView)findViewById(R.id.multiple_tv_recommend);
        multiple_tv_book_searchrecord = (MultipleTextView)findViewById(R.id.multiple_tv_book_searchrecord);
        rl_book_search_btn = (RelativeLayout)findViewById(R.id.rl_book_search_btn);
        iv_refresh_recommend = (ImageView)findViewById(R.id.iv_refresh_recommend);
        tv_recommend_name = (TextView)findViewById(R.id.tv_recommend_name);

        mModernLoadProgressBar = (ProgressBar_Modern)findViewById(R.id.progressbar_modern);
        common_loaddata_notice = (RelativeLayout)findViewById(R.id.common_loaddata_notice);
        common_prompt_content = (TextView)findViewById(R.id.common_prompt_content);
        common_refresh_net = (TextView)findViewById(R.id.common_refresh_net);
        circleProgressBar = (CircleProgressBar)findViewById(R.id.comon_bgbar_loading);

        WindowManager wm = this.getWindowManager();
        mBookBeanList = new ArrayList<>();

        BookSearchAdapter = new SearchContentAdapter(mContext, mBookBeanList);
        lv_book_search = (ListView)findViewById(R.id.lv_book_search);
        lv_book_search.addFooterView(search_foot_view);
        lv_book_search.setOverScrollMode(View.OVER_SCROLL_NEVER);
        lv_book_search.setAdapter(BookSearchAdapter);
    }

    @SuppressLint ("SetJavaScriptEnabled")
    @Override
    protected void initData() {
        drawable_back_tv = new BitmapDrawable(PublicUtil.getAlphaBitmap(PublicUtil.readBitMap(mContext, R.drawable.lk_back_small), Color.parseColor("#66ccdd")));
        iv_back.setImageDrawable(drawable_back_tv);
        search_foot_view.setVisibility(View.GONE);
        if (SPUtil.getBoolean("isKeywordSearch", true) && getIntent() != null) {
            mIsSearchRequestFinish = false;
            auto_tv_book_search.setText(getIntent().getStringExtra("keyword"));
            requestRecommendData(true);
            searchBookData();
            SPUtil.putBoolean("isKeywordSearch", false);
        }else {
            requestRecommendData(true);
            refreshSearchRecord();
        }
    }

    @Override
    protected void setListener() {
        auto_tv_book_search.setOnClickListener(this);
        rl_book_search_btn.setOnClickListener(this);
        iv_refresh_recommend.setOnClickListener(this);
        iv_clear_book_searchrecord.setOnClickListener(this);
        iv_clear_searchtext.setOnClickListener(this);
        back_layout.setOnClickListener(this);
        common_refresh_net.setOnClickListener(this);
        lv_book_search.setOnScrollListener(new AbsListView.OnScrollListener() {
            @Override
            public void onScrollStateChanged(AbsListView absListView, int scrollState) {
                // 当不滚动时
                if (scrollState == AbsListView.OnScrollListener.SCROLL_STATE_IDLE) {
                    // 判断是否滚动到底部
                    if (absListView.getLastVisiblePosition() == absListView.getCount() - 1) {
                        //加载更多功能的代码
                        if (ActivityUitl.isNetworkAvailable(BookSearchActivity.this) || BookSearchAdapter.getCount() <= 0) {
                            if(data!=null && data.getData().getBookList().size() == 0 && mCurrentPage > 1){
                                search_foot_view.setVisibility(View.VISIBLE);
                                return;
                            }
                            if (mIsSearchRequestFinish) {
                                mModernLoadProgressBar.setShow();
                                mIsSearchRequestFinish = false;
                                requestSearchData();
                            }
                        }else {
                            SnackBarNotice.customSnackbarShow(back_layout, R.string.laikan_network_anomaly);
                        }
                    }
                }
            }

            @Override
            public void onScroll(AbsListView absListView, int i, int i1, int i2) {

            }
        });
        lv_book_search.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                if (mBookBeanList.size() > 0 && position < mBookBeanList.size()) {
                    Intent intent = new Intent(mContext, BookDesActivity.class);
                    intent.putExtra("bookId", mBookBeanList.get(position).getId());
                    startActivity(intent);
                }
            }
        });
        auto_tv_book_search.addTextChangedListener(this);
        auto_tv_book_search.setOnFocusChangeListener(new OnFocusChangeListener() {

            @Override
            public void onFocusChange(View v, boolean hasFocus) {

                InputMethodManager imm = ((InputMethodManager)getSystemService(INPUT_METHOD_SERVICE));
                if (!hasFocus) {
                    imm.hideSoftInputFromWindow(auto_tv_book_search.getWindowToken(), 0);
                }else {
                    imm.hideSoftInputFromWindow(auto_tv_book_search.getWindowToken(), 0);
                }

            }
        });
        auto_tv_book_search.setOnEditorActionListener(new OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

                if (actionId == EditorInfo.IME_ACTION_SEARCH) {
                    // 先隐藏键盘
                    ((InputMethodManager)auto_tv_book_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(BookSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    searchBookData();
                    return true;
                }
                return false;
            }

        });
    }

    @Override
    public void onClick(View v) {
        // 这里可以设定：当搜索成功时，才执行保存操作
        switch (v.getId()) {
            case R.id.common_refresh_net:
                common_refresh_net.setOnClickListener(null);
                circleProgressBar.setVisibility(View.VISIBLE);
                mLoadDelaynternalTime = System.currentTimeMillis() + 2000;
                if (ActivityUitl.isNetworkAvailable(BookSearchActivity.this)) {
                    resetData();
                    searchBookData();
                }else {
                    closeDelayLoading(System.currentTimeMillis());
                }
                break;
            case R.id.back_layout:
                if (mIsBookSearchList) {
                    auto_tv_book_search.setText("");
                    mIsBookSearchList = false;
                    lv_book_search.setVisibility(View.GONE);
                    search_scroll.setVisibility(View.VISIBLE);
                    common_loaddata_notice.setVisibility(View.GONE);
                    auto_tv_book_search.clearFocus();
                }else{
                    finish();
                    if (BookSearchActivity.this.getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                        ((InputMethodManager)auto_tv_book_search.getContext().getSystemService(Context.INPUT_METHOD_SERVICE)).hideSoftInputFromWindow(BookSearchActivity.this.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
                    }
                    if (getWindow().getAttributes().softInputMode == WindowManager.LayoutParams.SOFT_INPUT_STATE_UNSPECIFIED) {
                        // 隐藏软键盘
                        getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
                    }
                    auto_tv_book_search.clearFocus();
                    //                    setTextEditable(false);
                }
                break;
            case R.id.auto_tv_book_search:
                auto_tv_book_search.setCursorVisible(true);
                //                initAutoComplete("history", auto_tv_book_search);
                auto_tv_book_search.showDropDown();
                break;
            case R.id.rl_book_search_btn:
                if (mIsSearchRequestFinish) {
                    mIsSearchRequestFinish = false;
                    searchBookData();
                }
                break;
            case R.id.iv_refresh_recommend:
                requestRecommendData(true);
                break;
            case R.id.iv_clear_book_searchrecord:
                SPUtil.putString("history", "");
                refreshSearchRecord();
                break;
            case R.id.iv_clear_searchtext:
                auto_tv_book_search.setText("");
                searchContent = "";
                resetData();
                mIsBookSearchList = false;
                auto_tv_book_search.clearFocus();
                search_scroll.setVisibility(View.VISIBLE);
                lv_book_search.setVisibility(View.GONE);
                common_loaddata_notice.setVisibility(View.GONE);
                break;
            default:
                break;
        }
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {

    }

    @Override
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
        if (auto_tv_book_search.getText() != null && auto_tv_book_search.getText().length() > 0) {
            iv_clear_searchtext.setVisibility(View.VISIBLE);
        }else {
            iv_clear_searchtext.setVisibility(View.GONE);
        }
    }

    //    private void setTextEditable(boolean isEditable) {
    //        if (isEditable) {
    //            auto_tv_book_search.setFocusableInTouchMode(true);
    //            auto_tv_book_search.setFocusable(true);
    //            auto_tv_book_search.requestFocus();
    //        }else {
    //            auto_tv_book_search.clearFocus();
    //            auto_tv_book_search.setFocusable(false);
    //        }
    //    }

    /**
     * 初始化AutoCompleteTextView，最多显示5项提示，使 AutoCompleteTextView在一开始获得焦点时自动提示
     *
     * @param field 保存在sharedPreference中的字段名
     * @param auto 要操作的AutoCompleteTextView
     */
    //    private void initAutoComplete(String field, AutoCompleteTextView auto) {
    //        String longhistory = SPUtil.getString("history", "");
    //        final String[] hisArrays = longhistory.split(",");
    //        ArrayAdapter<String> adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, hisArrays);
    //        // 只保留最近的50条的记录
    //        if (hisArrays.length > 50) {
    //            String[] newArrays = new String[50];
    //            System.arraycopy(hisArrays, 0, newArrays, 0, 50);
    //            adapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, newArrays);
    //        }
    //
    //        auto.setOnItemClickListener(new OnItemClickListener() {
    //
    //            @Override
    //            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
    //
    //                searchContent = hisArrays[position];
    //                saveHistory("history", auto_tv_book_search);
    //                search();
    //                mIsBookSearchList = true;
    //            }
    //        });
    //
    //    }

    /**
     * 把指定AutoCompleteTextView中内容保存到sharedPreference中指定的字符段
     *
     */
    //    private void saveHistory(String field, AutoCompleteTextView auto) {
    //        String text = auto.getText().toString();
    //        String longhistory = SPUtil.getString(field, "");
    //        if (!longhistory.contains(text + ",")) {
    //            StringBuilder sb = new StringBuilder(longhistory);
    //            sb.insert(0, text + ",");
    //            SPUtil.putString("history", sb.toString());
    //        }
    //    }
    private void saveHistory(AutoCompleteTextView auto_tv) {
        String keyword = auto_tv.getText().toString();
        String searchRecord = SPUtil.getString("history", "");
        if (!searchRecord.contains(keyword + ",")) {
            StringBuilder sb = new StringBuilder(searchRecord);
            sb.insert(0, keyword + ",");
            SPUtil.putString("history", sb.toString());
        }
    }

    private void refreshSearchRecord() {
        multiple_tv_book_searchrecord.removeAllViews();
        String searchRecord = SPUtil.getString("history", "");
        mBookSearchRecord = searchRecord.split(",");
        if (!TextUtils.isEmpty(searchRecord) && searchRecord.length() > 0) {
            List<String> searchHistoryList = new ArrayList<String>();
            for (int i = 0; i < mBookSearchRecord.length; i++) {
                searchHistoryList.add(mBookSearchRecord[i]);
            }
            multiple_tv_book_searchrecord.setOnMultipleTVItemClickListener(multipleRecordItemListener);
            multiple_tv_book_searchrecord.setTextViews(searchHistoryList);
        }
    }

    private void setView(BaseDataBean<SearchData> result) {
        multiple_tv_recommend.removeAllViews();
        tv_recommend_name.setText(result.getData().getRecommentName());
        multiple_tv_recommend.setOnMultipleTVItemClickListener(multipleRecommendItemListener);
        multiple_tv_recommend.setTextViews(result.getData().getBookNameArray());
    }

    /**
     * 获取推荐数据
     */
    private void requestRecommendData(boolean isloading) {
        if (isloading) {
            showDialog();
        }
        mRecommendDataList.clear();
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                // 成功返回时解析json数据
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseDataBean<SearchData>>() {
                    }.getType();
                    BaseDataBean<SearchData> result;
                    result = gson.fromJson(httpResponse.responseContent, type);
                    if (result != null) {
                        if (null == result.getData() || !Constants.RESULT_OK.equals(result.getResult())) {
                            common_prompt_content.setText(R.string.laikan_data_load_failed);
                            closeDelayLoading(System.currentTimeMillis());
                        }else {
                            common_refresh_net.setOnClickListener(BookSearchActivity.this);
                            mRecommendDataList = result.getData().getBookNameArray();
                            search_scroll.setVisibility(View.VISIBLE);
                            common_loaddata_notice.setVisibility(View.GONE);
                            lv_book_search.setVisibility(View.GONE);
                            setView(result);
                        }
                    }else {
                        common_prompt_content.setText(R.string.laikan_data_load_failed);
                        closeDelayLoading(System.currentTimeMillis());
                    }

                }catch (JsonSyntaxException e) {
                    // 数据解析失败
                    common_prompt_content.setText(R.string.laikan_data_load_failed);
                    closeDelayLoading(System.currentTimeMillis());
                    e.printStackTrace();
                    return;
                }

            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                common_prompt_content.setText(R.string.laikan_network_anomaly);
                closeDelayLoading(System.currentTimeMillis());
                KLog.e("网络不给力，请重试。56");
            }

            @Override
            public void onFinish() {
                dismissDialog();
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "recomment_bookName");
        HttpApiRequestEngine.getInstance().httpGetRequest(requester, requestListener);
    }

    /**
     * 访问接口获取数据
     */
    BaseDataBean<SearchData<Search>> data;

    private void requestSearchData() {
        HashMap<String, String> map = new HashMap<>();
        map.put("queryString", searchContent);
        map.put("page", mCurrentPage + "");
        RequestListener requestListener = new RequestListener() {
            @Override
            public void onPreExecute() {
                KLog.e("---------volley onPreExecute!!!");
            }

            @Override
            public void onSuccess(HttpResponse httpResponse) {
                // 成功返回时解析json数据
                try {
                    Gson gson = new Gson();
                    Type type = new TypeToken<BaseDataBean<SearchData<Search>>>() {}.getType();

                    data = gson.fromJson(httpResponse.responseContent, type);
                    if (data != null) {
                        if (data.getData() == null || !Constants.RESULT_OK.equals(data.getResult())) {
                            ToastMgr.showShortToast(data.getError_msg());
                        }else {
                            mIsBookSearchList = true;
                            common_refresh_net.setOnClickListener(BookSearchActivity.this);
                            mBookBeanList.addAll(data.getData().getBookList());
                            BookSearchAdapter.setDatas(mBookBeanList);
                            if (data.getData().getBookList().size() == 0 && mCurrentPage == 1) {
                                ToastMgr.showShortToast(R.string.request_no_data);
                                search_foot_view.setVisibility(View.GONE);
                            } else if(data.getData().getBookList().size() == 0 && mCurrentPage > 1){
                                search_foot_view.setVisibility(View.VISIBLE);
                            }
                            lv_book_search.setVisibility(View.VISIBLE);
                            search_scroll.setVisibility(View.GONE);
                            common_loaddata_notice.setVisibility(View.GONE);
                        }
                    }else {
                        common_prompt_content.setText(R.string.laikan_data_load_failed);
                        closeDelayLoading(System.currentTimeMillis());
                    }
                    mCurrentPage++;
                }catch (Exception e) {
                    // 数据解析失败
                    common_prompt_content.setText(R.string.laikan_data_load_failed);
                    closeDelayLoading(System.currentTimeMillis());
                    e.printStackTrace();
                    return;
                }
            }

            @Override
            public void onError(VolleyErrorHandler errorHandler) {
                common_prompt_content.setText(R.string.laikan_network_anomaly);
                closeDelayLoading(System.currentTimeMillis());
                KLog.e("网络不给力，请重试。57");
            }

            @Override
            public void onFinish() {
                mModernLoadProgressBar.setHide();
                mIsSearchRequestFinish = true;
            }
        };

        Requester requester = new Requester();
        requester.setUrl(APIProtocol.getRootURL2() + "search");
        requester.setMapBody(map);
        HttpApiRequestEngine.getInstance().httpPostRequest(requester, requestListener);
    }

    public void closeDelayLoading(long currenttime) {
        if (currenttime < mLoadDelaynternalTime) {
            new Handler().postDelayed(new Runnable() {

                @Override
                public void run() {
                    requestDataFailedHandle();
                }
            }, 1000);
        }else {
            requestDataFailedHandle();
        }
    }

    private void requestDataFailedHandle() {
        common_refresh_net.setOnClickListener(BookSearchActivity.this);
        lv_book_search.setVisibility(View.GONE);
        search_scroll.setVisibility(View.GONE);
        common_loaddata_notice.setVisibility(View.VISIBLE);
        circleProgressBar.setVisibility(View.INVISIBLE);
    }

    private void resetData() {
        search_foot_view.setVisibility(View.GONE);
        mCurrentPage = 1;
        BookSearchAdapter.cleanDatas();

    }

    OnMultipleTVItemClickListener multipleRecommendItemListener = new OnMultipleTVItemClickListener() {
        @Override
        public void onMultipleTVItemClick(View view, int position) {
            if (mIsSearchRequestFinish) {
                mIsSearchRequestFinish = false;
                auto_tv_book_search.setText(mRecommendDataList.get(position));
                searchContent = mRecommendDataList.get(position);
                auto_tv_book_search.setSelection(auto_tv_book_search.getText().length()); //将光标移动到最后
                searchBookData();
            }
        }
    };

    OnMultipleTVItemClickListener multipleRecordItemListener = new OnMultipleTVItemClickListener() {
        @Override
        public void onMultipleTVItemClick(View view, int position) {
            if (mIsSearchRequestFinish) {
                mIsSearchRequestFinish = false;
                auto_tv_book_search.setText(mBookSearchRecord[position]);
                searchContent = mBookSearchRecord[position];
                auto_tv_book_search.setSelection(auto_tv_book_search.getText().length()); //将光标移动到最后
                searchBookData();
            }
        }
    };

    private void hideSoftkeyBoard(View view){
        InputMethodManager inputMethodManager = (InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
        if(inputMethodManager != null){
            inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(),0);
        }
    }

}